import wepy from 'wepy'

export default class extends wepy.mixin { 
  data = {
    value: '',
    searchList: [],
    kwList: []
  }

  onLoad() {
    this.kwList = wepy.getStorageSync('kw') || []
  }

  methods = {
    onChange(e) {
      this.value = e.detail
      if(e.detail.trim().length <= 0) {
        this.searchList = []
        return 
      }

      this.getSearchList(e.detail)
    },

    onCancel(e) {
      console.log(e)
    },
  
    onSearch(e) {
      let kw = e.detail.trim()
      if(kw.length <= 0) {
        this.searchList = []
        return 
      }

      if(!this.kwList.includes(kw)) {
        this.kwList.unshift(kw)
      }
      
      this.kwList = this.kwList.slice(0, 10)
      wepy.setStorageSync('kw', this.kwList)
      
      wepy.navigateTo({
        url: '/pages/goods_list?search=' + e.detail
      })
    },

    goGoodDetail(id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?id=' + id
      })
    },

    goGoodsList(search) {
      wepy.navigateTo({
        url: '/pages/goods_list?search=' + search
      })
    },

    clearHistory() {
      this.kwList = []
      wepy.setStorageSync('kw', [])
    }

  }

  async getSearchList(query) {
    let { data: res } = await wepy.get('/goods/qsearch', {query})

    if(res.meta.status !== 200) {
      return wepy.baseToast()
    }

    this.searchList = res.message
    this.$apply()
  }
}